import router from './router'
import NProgress from 'nprogress'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })
let hasRoles = true
const whiteList = ['/login/index', '/register']
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()
  if (userStore.getToken) {
    if (to.path === '/login/index') {
      next({ path: '/' })
      NProgress.done()
    } else {
      try {
        const accessRoutes = await permissionStore.GenerateRoutes()
        if (hasRoles) {
          accessRoutes.forEach((route) => {
            router.addRoute(route)
          })
          hasRoles = false
          next({ ...to, replace: true })
        } else {
          next()
        }
      } catch (e) {
        console.log(e)
      }

      NProgress.done()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录名单，直接进入
      next()
    } else {
      next(`/login/index`)
      NProgress.done()
    }
  }
  NProgress.start()
})
router.afterEach(() => {
  NProgress.done()
})